﻿

using System;

namespace n_Data
{
public static class Const
{
	public static int Parse( string s )
	{
		s = s.ToLower();
		if( s.StartsWith( "0x" ) ) {
			s = s.Remove( 0, 2 );
			return int.Parse( s, System.Globalization.NumberStyles.HexNumber );
		}
		else {
			return int.Parse( s );
		}
	}
}
public static class Data
{
	//读取一个有符号数字节到一个符号数
	public static long GetInt8( byte[] BASE, int Addr )
	{
		long data = BASE[ Addr ];
		if( ( data & 0x00000080 ) != 0 ) {
			data = -( ( data ^ 0xffffffff ) + 1 );
		}
		return data;
	}
	
	//合并2个字节到一个有符号数
	public static long GetInt16( byte[] BASE, int Addr )
	{
		long data = BASE[ Addr ];
		data += BASE[ Addr + 1 ] * 256u;
		if( ( data & 0x00008000 ) != 0 ) {
			data = -( ( data ^ 0xffffffff ) + 1 );
		}
		return data;
	}
	
	//合并4个字节到一个有符号数
	public static long GetInt32( byte[] BASE, int Addr )
	{
		long data = BASE[ Addr ];
		data += BASE[ Addr + 1 ] * 256u;
		data += BASE[ Addr + 2 ] * 256u * 256u;
		data += BASE[ Addr + 3 ] * 256u * 256u * 256u;
		if( ( data & 0x80000000 ) != 0 ) {
			data = -( ( data ^ 0xffffffff ) + 1 );
		}
		return data;
	}
	
	//合并1个字节到一个无符号数
	public static long GetUint8( byte[] BASE, int Addr )
	{
		long data = BASE[ Addr ];
		
		return data;
	}
	
	//合并2个字节到一个无符号数
	public static long GetUint16( byte[] BASE, int Addr )
	{
		long data = BASE[ Addr ];
		data += BASE[ Addr + 1 ] * 256u;
		
		return data;
	}
	
	//合并4个字节到一个无符号数
	public static long GetUint32( byte[] BASE, int Addr )
	{
		long data = BASE[ Addr ];
		data += BASE[ Addr + 1 ] * 256u;
		data += BASE[ Addr + 2 ] * 256u * 256u;
		data += BASE[ Addr + 3 ] * 256u * 256u * 256u;
		
		return data;
	}
	
	//分解一个有符号数到buf
	public static void SetInt32( byte[] BASE, int Addr, long Data )
	{
		ulong Data1;
		if( Data < 0 ) {
			Data1 = (ulong)-Data;
			Data1 ^= 0xffffffff;
			Data1 += 1;
		}
		else {
			Data1 = (ulong)Data;
		}
		BASE[ Addr ] = (byte)( Data1 % 256u );
		BASE[ Addr + 1 ] = (byte)( Data1 / 256u % 256u );
		BASE[ Addr + 2 ] = (byte)( Data1 / 256u / 256u % 256u );
		BASE[ Addr + 3 ] = (byte)( Data1 / 256u / 256u / 256u % 256u );
	}
}
}





